﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using TruckScale.Helpers;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.Models
{
  public class HardwareConfigModel
  {
    public int? AutoNo { get; set; }
    public string ConfigKey { get; set; }
    public string ConfigValue { get; set; }

    public static Dictionary<string, string> SelectConfig()
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = "select * from hardwareconfig;";
          IEnumerable<HardwareConfigModel> output = cnn.Query<HardwareConfigModel>(sql);

          return output.ToDictionary(o => o.ConfigKey, o => o.ConfigValue);
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);

          Dictionary<string, string> _DefaultHardwareConfig = new Dictionary<string, string>
          {
            {"IOEnable", "False" },
            {"QR1Enable", "False" },
            {"QR2Enable", "False" },
            {"RF1Enable", "False" },
            {"RF2Enable", "False" },
            {"AxleEnable", "False" },
            {"LPR1Enable", "False" },
            {"LPR2Enable", "False" },
            {"Monitor1Enable", "False" },
            {"Monitor2Enable", "False" },
            {"Monitor3Enable", "False" },
            {"Monitor4Enable", "False" },
            {"LED1Enable", "False" },
            {"LED2Enable", "False" },
            {"GratingEnable", "False" }
          };
          return _DefaultHardwareConfig;
        }
      }
    }

    public static int UpdateConfig(Dictionary<string, string> config)
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          List<HardwareConfigModel> configList = new List<HardwareConfigModel>();
          config.ToList().ForEach(c =>
          {
            HardwareConfigModel cm = new HardwareConfigModel()
            {
              ConfigKey = c.Key,
              ConfigValue = c.Value
            };
            configList.Add(cm);
          });
          string sql = @"update hardwareconfig set config_value = @ConfigValue where config_key = @ConfigKey;";
          return cnn.Execute(sql, configList);
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return -1;
        }
      }
    }
  }
}
